﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CustomsNuke.Engine.CustomsException;
using Quartz;
using CustomsNuke.Scheduling.Utility;
using CustomsNuke.Engine.Data;

namespace CustomsNuke.Scheduling.Jobs
{
    class CustomsContainerLadingJob : IJob
    {
        CustomsNukeContext _customsNukeContext = new CustomsNukeContext();
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                int taskId = int.Parse(context.JobDetail.Key.Name);
                //Step 1:通过ID取到Parameters
                Task currTask = _customsNukeContext.Task.FirstOrDefault(x => x.Id == taskId && x.IsDeleted == false);
                if (currTask == null)
                {
                    Global.Current.Scheduler.DeleteJob(context.JobDetail.Key);
                    return;
                }

                string containerNo = currTask.ParameterContainerNumber;
                string shipName = currTask.ParameterConveyance;
                string shipNo = currTask.ParameterVoyageNumber;
                string dock = currTask.ParameterDock;

                //step 2:如果Parameters不存在，就去取电子装箱单数据
                if (string.IsNullOrEmpty(containerNo))
                {
                    Global.Current.Scheduler.DeleteJob(context.JobDetail.Key);
                    currTask.TaskStateId = 5;
                    _customsNukeContext.SaveChanges();
                    return;
                }
                if (string.IsNullOrEmpty(shipName) || string.IsNullOrEmpty(shipNo))
                {
                    LadingResult ladingResult = CustomsAnalysUtils.GetLadingInfo(containerNo, "", "");
                    if (ladingResult.IsSuccess)
                    {
                        //取到装箱单数据对应两条以上的船
                        if (ladingResult.IsNeedMoreInfo)
                        {
                            //取进出门信息
                            CodecoResult codecoResult = CustomsAnalysUtils.GetCodecoInfo(containerNo);
                            //如果取到了进出门信息
                            if (codecoResult.IsSuccess)
                            {
                                //判断进门信息是否在电子装箱单的列表中。
                                if (ladingResult.ErrorMessage.Contains(codecoResult.ShipName) &&
                                    ladingResult.ErrorMessage.Contains(codecoResult.ShipNo))
                                {
                                    //如果在的话，再次查询一次电子装箱单。
                                    LadingResult ladingResult2 = CustomsAnalysUtils.GetLadingInfo(containerNo,
                                                                                                  codecoResult.ShipName,
                                                                                                  codecoResult.ShipNo);

                                    if (ladingResult2.IsSuccess)
                                    {
                                        shipName = ladingResult2.ShipName;
                                        shipNo = ladingResult2.ShipNo;
                                        dock = ladingResult2.Dock;
                                        //回写Parameters
                                        currTask.ParameterConveyance = shipName;
                                        currTask.ParameterVoyageNumber = shipNo;
                                        currTask.ParameterDock = dock;
                                    }
                                }
                                else
                                {
                                    currTask.WarningMessage = ladingResult.ErrorMessage;
                                    currTask.TaskStateId = 3;
                                    Global.Current.Scheduler.PauseJob(context.JobDetail.Key);
                                }
                            }
                            else
                            {
                                currTask.WarningMessage = ladingResult.ErrorMessage;
                                currTask.TaskStateId = 3;
                                Global.Current.Scheduler.PauseJob(context.JobDetail.Key);
                            }
                        }
                        else
                        {
                            shipName = ladingResult.ShipName;
                            shipNo = ladingResult.ShipNo;
                            dock = ladingResult.Dock;
                            //回写Parameters
                            currTask.ParameterConveyance = shipName;
                            currTask.ParameterVoyageNumber = shipNo;
                            currTask.ParameterDock = dock;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(dock))
                {
                    OnboardingResult result = CustomsAnalysUtils.GetOnboardingInfo(containerNo, dock);
                    if (result.IsSuccess)
                    {
                        ContainerLading lading =
                            _customsNukeContext.ContainerLading.FirstOrDefault(
                                x => x.TaskId == currTask.Id && !x.IsDeleted);
                        if (lading != null)
                        {
                            lading.Admitted = result.IsAdmitted;
                            lading.Assigned = result.IsOnboarding;
                            lading.ContainerNumber = containerNo;
                            lading.Dock = dock;
                            lading.Conveyance = shipName;
                            lading.EnteredDate = string.IsNullOrEmpty(result.EnteredDate.Trim())
                                                     ? DateTime.MinValue
                                                     : DateTime.Parse(result.EnteredDate);
                            lading.LadingComment = result.EnteredMode;
                            lading.LadingStatus = result.LeftMode;
                            lading.LeftDate = string.IsNullOrEmpty(result.LeftDate.Trim())
                                                  ? DateTime.MinValue
                                                  : DateTime.Parse(result.LeftDate);
                            lading.VoyageNumber = shipNo;
                        }
                        else
                        {
                            lading = new ContainerLading();
                            lading.Admitted = result.IsAdmitted;
                            lading.Assigned = result.IsOnboarding;
                            lading.ContainerNumber = containerNo;
                            lading.Conveyance = shipName;
                            lading.CreatedDate = DateTime.Now;
                            lading.EnteredDate = string.IsNullOrEmpty(result.EnteredDate.Trim())
                                                     ? DateTime.MinValue
                                                     : DateTime.Parse(result.EnteredDate);
                            lading.LadingComment = result.EnteredMode;
                            lading.LadingStatus = result.LeftMode;
                            lading.LeftDate = string.IsNullOrEmpty(result.LeftDate.Trim())
                                                  ? DateTime.MinValue
                                                  : DateTime.Parse(result.LeftDate);
                            lading.ModifiedDate = DateTime.Now;
                            lading.TaskId = taskId;
                            lading.Dock = dock;
                            lading.VoyageNumber = shipNo;
                            lading.WarningMessage = "";

                            _customsNukeContext.AddToContainerLading(lading);
                        }
                        if (result.IsOnboarding)
                        {
                            currTask.TaskStateId = 4;
                            Global.Current.Scheduler.DeleteJob(context.JobDetail.Key);
                        }
                    }
                }
                if (context.NextFireTimeUtc == null)
                {
                    currTask.TaskStateId = 4;
                }

                _customsNukeContext.SaveChanges();
            }
            catch (Exception ex)
            {
                CustomsExceptionManager.HandleException(ex, ExceptionType.NothrowException);
            }
        }
    }
}
